package com.nulldev.util.io.lzma;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.nulldev.util.io.cstreams.Coder;
import com.nulldev.util.io.lzma.lzma.Decoder;

public class LZMADecoderWrapper implements Coder {
	private final Decoder decoder;

    public LZMADecoderWrapper(final Decoder decoder)
    {
        this.decoder = decoder;
    }

    @Override
    public void code(final InputStream in, final OutputStream out)
            throws IOException
    {
        byte[] properties = new byte[5];
        if (in.read(properties) != 5)
        {
            throw new IOException("LZMA file has no header!");
        }

        if (!decoder.setDecoderProperties(properties))
        {
            throw new IOException("Decoder properties cannot be set!");
        }

		long outSize = 0;
		for (int i = 0; i < 8; i++)
		{
			int v = in.read();
			if (v < 0)
				throw new IOException("Can't read stream size");
			outSize |= ((long)v) << (8 * i);
		}

        if (!decoder.code(in, out, outSize))
        {
            throw new IOException("Decoding unsuccessful!");
        }
    }
}
